# -*- coding: utf-8 -*-

#-------------------------------------------------------------------------------
# Name：conftest
# Description:
# @Author: macy mei
# @Date:   2019/11/6
# @Last Modified by:   macy mei
# @Last Modified time: 2019/11/6 上午11:21
#-------------------------------------------------------------------------------
import sys,os,requests,json
import pytest
sys.path.append(os.path.dirname(os.path.realpath(__file__))+"/../")
from src.common.globals import set_value,get_value
from src.utils.conf.conf import GetConfigs
from src.utils.log.logger import Logger


@pytest.fixture(autouse=True)
def get_cookies(user="superadmin",pwd="hgr4PVo3NuF6G0GmF3f/hg=="):
    #get_host_conf()
    host = get_value("host")
    print("host--------,", host)
    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json"
    }
    #判断是否登录
    def find_islogin():
        find_login_url = "{host}:10030/api/auth/isLogin".format(host=host)
        response = requests.get(find_login_url, headers=headers, cookies=get_value("cookies"))
        result = json.loads(response.text)
        if isinstance(result, (dict)):
            if 'success' in result.keys():
                return result["success"]
    #如果非登录状态，则重新登录
    if not find_islogin():
        login_url="{host}:10030/api/auth/login".format(host=host)
        login_params={
              "autoLogin": "N",
              "password":pwd,
              "userNo":user
            }

        response = requests.post(login_url, headers=headers, data=json.dumps(login_params))
        result = json.loads(response.text)
        if isinstance(result, (dict)):
            if 'success' in result.keys():
                if result["success"] == True:
                    JSESSIONID=result["payload"]["data"]["sessionId"]
                    cookie_str=r"JSESSIONID={0};path=/;domain={1}".format(JSESSIONID,host)
                    cookies = {}
                    for line in cookie_str.split(';'):
                        value = line.split('=',1)
                        cookies[value[0]] = value[1]
                    #将本次登录cookies放置全局变量，供后续case使用
                    set_value("cookies", cookies)
                else:
                    pytest.exit(u"登录失败，停止执行用例")
                    if result["message"]["desc"]:
                        Logger("ERROR").log(result["message"]["desc"])
                    else:
                        Logger("ERROR").log("login fail")